﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WXDba.Entity;
using WXDba.Abstract;
using Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WXPackage
{
    /// <summary>
    /// 用户分组管理
    /// 参考文档：http://mp.weixin.qq.com/wiki/5/0d8acdd6d4433c877fbea938a2f133cd.html
    /// </summary>
    public class GroupManage : BaseManage
    {
        IUserGroup _IGroup = ConcreteFactory.GetUserGroup();

        #region 远程操作
        /// <summary>
        /// 获取远程分组列表
        /// </summary>
        /// <returns></returns>
        public List<UserGroup> GetList_Remove()
        {
            string url = new LinkManage().GetGroupList();
            string result = NetHelper.Get(url);
            try
            {
                JObject obj = JObject.Parse(result);
                JToken groups = obj["groups"];
                if (groups != null)
                {
                    List<UserGroup> list = JsonConvert.DeserializeObject<List<UserGroup>>(groups.ToString());
                    return list;
                }
                throw new Exception("返回groups为空");
            }
            catch (Exception ex)
            {
                throw new Exception("解析返回结果失败，" + ex.Message);
            }
        }
        /// <summary>
        /// 获取远程用户所在的分组
        /// </summary>
        /// <param name="OpenID">OpenID</param>
        /// <returns></returns>
        public int GetGroupID_Remove(string OpenID)
        {
            if (string.IsNullOrEmpty(OpenID))
                throw new Exception("OpenID不能为空");
            string url = new LinkManage().GetUser_Group();
            string result = NetHelper.Post(url,
                new { openid = OpenID }.ToJsonString());
            JObject obj = JObject.Parse(result);
            if (obj["groupid"] != null)
            {
                return Convert.ToInt32(obj["groupid"]);
            }
            throw new Exception("调用远程接口失败," + result);
        }
        /// <summary>
        /// 创建分组
        /// 一个公众账号，最多支持创建100个分组。
        /// </summary>
        /// <param name="Name">菜单名称</param>
        /// <returns></returns>
        public bool Create(string Name)
        {
            if (string.IsNullOrEmpty(Name))
                throw new Exception("菜单名称不能为空");
            string url = new LinkManage().GetCreateGroup();
            string result = NetHelper.Post(url,
                new { group = new { name = Name } }.ToJsonString());
            //处理相应结果
            JObject obj = JObject.Parse(result);
            if (obj["group"] != null)
            {
                int id = Convert.ToInt32(obj.SelectToken("group.id"));
                string name = (string)obj.SelectToken("group.name");
                //创建分组成功
                return _IGroup.Add(new UserGroup()
                {
                    ID = id,
                    Name = name,
                    AddTime = DateTime.Now
                });
            }
            throw new Exception(result);
        }
        /// <summary>
        /// 修改分组名称,注意系统分组不能修改或删除
        /// 0	未分组
        ///1	黑名单
        ///2	星标组
        /// </summary>
        /// <param name="ID">分组ID</param>
        /// <param name="Name">分组名称</param>
        /// <returns></returns>
        public bool Update(int ID, string Name)
        {
            if (string.IsNullOrEmpty(Name))
                throw new Exception("分组名称不能为空");
            string url = new LinkManage().GetUpdateGroup();
            string result = NetHelper.Post(url,
                new { group = new { id = ID, name = Name } }.ToJsonString());
            JObject obj = JObject.Parse(result);
            if ((string)obj["errcode"] == "0")
            {
                //修改成功
                //同步本地
                _IGroup.UpdateName(ID, Name);
                return true;
            }
            throw new Exception("调用远程接口出错，" + result);
        }
        /// <summary>
        /// 移动指定用户到分组
        /// </summary>
        /// <param name="OpenID">OpenID</param>
        /// <param name="GroupID">分组ID</param>
        /// <returns></returns>
        public bool Move(string OpenID, int GroupID)
        {
            string url = new LinkManage().GetMoveUser_Group();
            string result = NetHelper.Post(url,
                new { openid = OpenID, to_groupid = GroupID }.ToJsonString());
            JObject obj = JObject.Parse(result);
            if ((string)obj["errcode"] == "0")
            {
                //移动用户分组成功
                IWXUser _IUser = ConcreteFactory.GetWXUser();
                _IUser.UpdateGroup(new List<string>() { OpenID }, GroupID);
                return true;
            }
            throw new Exception("调用远程接口失败，" + result);
        }
        /// <summary>
        /// 批量修改用户分组
        /// </summary>
        /// <param name="idList">OpenID列表</param>
        /// <param name="GroupID">分组ID</param>
        /// <returns></returns>
        public bool Move(List<string> idList, int GroupID)
        {
            string url = new LinkManage().GetMoveUsers_Group();
            string result = NetHelper.Post(url,
                new { openid_list = idList, to_groupid = GroupID }.ToJsonString());
            JObject obj = JObject.Parse(result);
            if ((string)obj["errcode"] == "0")
            {
                //批量移动用户成功
                ConcreteFactory.GetWXUser().UpdateGroup(idList, GroupID);
                return true;
            }
            throw new Exception("远程调用接口失败，" + result);
        }
        /// <summary>
        /// 删除分组
        /// </summary>
        /// <param name="GroupID">分组ID</param>
        /// <returns></returns>
        public bool Remove(int GroupID)
        {
            string url = new LinkManage().GetDeleteGroup();
            string result = NetHelper.Post(url,
                new { group = new { id = GroupID } }.ToJsonString());
            JObject obj = JObject.Parse(result);
            if ((string)obj["errcode"] == "0")
            {
                //删除分组成功
                _IGroup.Delete(GroupID);
                return true;
            }
            throw new Exception("调用远程接口失败," + result);
        }
        #endregion

        #region 本地操作
        /// <summary>
        /// 同步用户分组
        /// </summary>
        /// <returns></returns>
        public bool SyncList()
        {
            List<UserGroup> groups = GetList_Remove();
            return _IGroup.Replace(groups);
        }
        /// <summary>
        /// 获取本地分组列表
        /// </summary>
        /// <returns></returns>
        public List<UserGroup> GetList()
        {
            return _IGroup.GetList();
        }
        /// <summary>
        /// 获取指定用户的GroupID
        /// </summary>
        /// <param name="OpenID"></param>
        /// <returns></returns>
        public int? GetGroupID(string OpenID)
        {
            WXUser user = ConcreteFactory.GetWXUser().GetModel_OpenID(OpenID);
            if (user == null)
                throw new Exception("获取用户对象失败，OpenID=" + OpenID);
            return user.GroupID;
        }
        #endregion
    }
}
